package com.atguigu.hbase;

import com.sun.tools.corba.se.idl.StringGen;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;

public class HbaseDemo {

    public static void main(String[] args) throws IOException {
        //System.out.println(connection);
        //createTable(null ,  "emp" , "info1" , "info2");
        putData(null , "emp", "1001", "info1" , "name", "zhangxiaosan");

    }
    /**
     * DML - 插入数据/修改数据
     * put 'ns:tn' , 'rk'  , 'cf:cl' , 'v'
     */
    public static void putData(String namespace , String tableName , String rk, String cf, String cl , String value) throws IOException {
        //获取Table对象
        TableName tn = TableName.valueOf(namespace, tableName);
        Table table = connection.getTable(tn);
        Put put = new Put(Bytes.toBytes(rk));
        put.addColumn(Bytes.toBytes(cf) , Bytes.toBytes(cl) , Bytes.toBytes(value));
        table.put(put);

        table.close();
    }


    /**
     * DDL - 创建表
     * create 'ns:tn' , 'cf' ...
     */
    public static void createTable(String namespace , String tableName , String ... cfs ) throws IOException {
        //获取Admin对象
        Admin admin = connection.getAdmin();
        //先判断表是否已经存在
        TableName tn = TableName.valueOf(namespace, tableName);
        boolean exists = admin.tableExists(tn);
        if(exists){
            System.err.println((namespace==null?"default":namespace) + ":"+tableName +" 表已经存在");
            return ;
        }
        //创建表
        TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(tn);
        //设置列族
        for (String cf : cfs) {
            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder =
                    ColumnFamilyDescriptorBuilder.newBuilder(Bytes.toBytes(cf));
            ColumnFamilyDescriptor columnFamilyDescriptor = columnFamilyDescriptorBuilder.build();
            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptor);
        }

        TableDescriptor tableDescriptor = tableDescriptorBuilder.build();

        admin.createTable(tableDescriptor);
        System.out.println((namespace==null?"default":namespace) + ":"+tableName +" 表创建成功");
        admin.close();
    }

    /**
     * 创建connection对象
     */
    private static Connection connection ;

    static{
        //Configuration configuration = new Configuration();
        Configuration configuration = HBaseConfiguration.create();
        //指定hbase的地址
        configuration.set("hbase.zookeeper.quorum", "hadoop102,hadoop103,hadoop104");
        try {
            connection = ConnectionFactory.createConnection(configuration);
        } catch (IOException e) {

        }
    }

}
